
import com.ocpsoft.pretty.time.PrettyTime;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.Timer;
import twitter4j.ProfileImage;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Tweet;
import twitter4j.Twitter;
import twitter4j.TwitterException;

public class TimelinePane extends JPanel {

    public TimelinePane(Twitter twt, boolean needsUpdate,String inopt, Object in){
        if(in instanceof String){ KeyWord = (String) in; nquery = null;}
        if(in instanceof Query){  nquery = (Query) in; KeyWord = null;}
        opt = inopt;
        tw = twt;
        tm = new Timer(120000,reload);
        if(needsUpdate) tm.start();
        initContent();
        if(opt.equals("tweets")&&(in==null)) fupdate(KeyWord);
        else if(opt.equals("tweets")) update(KeyWord);
        if(opt.equals("search")) search(nquery);
        Thread th = new Thread(){
            public void run() {
            if(opt.equals("tweets")) update(KeyWord);
            }
            };
        th.start();
        this.setVisible(true);
    }

    private void initContent(){
        lista = new listLocalImgRef();
        labs = new JPanel(new java.awt.GridLayout(0, 1));
        labs.setBackground(Color.white);
        labs.setSize(600, 450);
        labels= new JLabel[50];
        for (int i=0;i<50;i++){
            labels[i]=new JLabel("message" + i);
        }
        sp = new javax.swing.JScrollPane();
        tx = new javax.swing.JTextPane();
        tx.setContentType("text/html");
        tx.setEditable(false);
        tx.setFocusable(false);
        sp.setViewportView(labs);
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(sp, javax.swing.GroupLayout.PREFERRED_SIZE, 650, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(sp, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 450, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
    }

    private String getImageURL(Status estatus){
    String  url = "";
       try {
            url = tw.getProfileImage(estatus.getUser().getScreenName(),ProfileImage.NORMAL).getURL();}
            catch( TwitterException ie){
            ie.printStackTrace();
            url = "https://si2.twimg.com/sticky/default_profile_images/default_profile_0_normal.png";}
         return url;
    }

    public void fupdate(String User){
        PrettyTime p = new PrettyTime();
        try {
            if(User!=null) statuses = tw.getUserTimeline(User);
            else statuses = tw.getFriendsTimeline();
        } catch (TwitterException ex) {} catch (IllegalStateException ex) {}
        try {
        for (int i = 0; i<statuses.size(); i++) {
                final Status status = statuses.get(i);
                labels[i].setIcon(
                        new javax.swing.JLabel() {
                        public javax.swing.Icon getIcon() {
                            try {
                                return new javax.swing.ImageIcon(
                                    new java.net.URL("https://si2.twimg.com/sticky/default_profile_images/default_profile_0_normal.png")
                                );
                            } catch (java.net.MalformedURLException e) {
                            }
                            return null;
                        }
                        }.getIcon()
                );
                labels[i].setText("<html><font face=\"arial\" color=#0000FF>@" + status.getUser().getScreenName() + ":</font><font face=\"arial\"> "+ status.getText()+"</font><br><font face=\"arial\" size=-2 color=#666666><i>"+p.format(status.getCreatedAt())+"</i></font></html>");
                labs.add(labels[i]);
                labels[i].setPreferredSize(new Dimension(630,50));
            }
            last = statuses.size();
        } catch (NullPointerException e) {} 
    }

    public void update(String User){
     //String data;
        PrettyTime p = new PrettyTime();
	System.out.println("updating now...");
        try {
            System.out.println("quedan " + tw.getRateLimitStatus().getRemainingHits() + " queries.");
        } catch (TwitterException ex) {}
        DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM);
        try {
            if(User!=null) statuses = tw.getUserTimeline(User);
            else statuses = tw.getFriendsTimeline();
        } catch (TwitterException ex) {} catch (IllegalStateException ex) {}
        for (int i = 0; i<statuses.size(); i++) {
                final Status status = statuses.get(i);
                if(!lista.exist(new LocalImgRef(status.getUser().getScreenName()))){
                    System.out.print("x");
                    lista.addImg(new LocalImgRef(status.getUser().getScreenName(),getImageURL(status)));
                }
                else System.out.print("o");
                labels[i].setIcon(
                        new javax.swing.JLabel() {
                        public javax.swing.Icon getIcon() {
                            try {
                                return new javax.swing.ImageIcon(
                                    new java.net.URL(lista.getBySearch(new LocalImgRef(status.getUser().getScreenName())).url)
                                );
                            } catch (java.net.MalformedURLException e) {
                            }
                            return null;
                        }
                        }.getIcon()
                );
                labels[i].setText("<html><font face=\"arial\" color=#0000FF>@" + status.getUser().getScreenName() + ":</font><font face=\"arial\"> "+ status.getText()+"</font><br><font face=\"arial\" size=-2 color=#666666><i>"+p.format(status.getCreatedAt())+"</i></font></html>");
             if(last<i){
                labs.add(labels[i]);
                labels[i].setPreferredSize(new Dimension(670,50));}
            }
        if(last>statuses.size()){
            for(int q = statuses.size();q<last;q++){
                labs.remove(labels[q]);
            }
        }
        last = statuses.size();
        try {
            System.out.println("\nupdate listo. se reinicia el contador de queries " + p.format(tw.getRateLimitStatus().getResetTime()));
            System.out.println("quedan "+tw.getRateLimitStatus().getRemainingHits()+" queries.");
        } catch (TwitterException ex) {}
    }

    public void search(Query buscar){
        PrettyTime p = new PrettyTime();
        try {
           QueryResult result = tw.search(buscar);
           tweets = result.getTweets();
        } catch (TwitterException ex) {} catch (IllegalStateException ex) {}
        try {
        for (int i = 0; i<tweets.size(); i++) {
                final Tweet tweet = tweets.get(i);
                labels[i].setText("<html><font face=\"arial\" color=#0000FF>@" + tweet.getFromUser() + ":</font><font face=\"arial\"> "+ tweet.getText()+"</font><br><font face=\"arial\" size=-2 color=#666666><i>"+p.format(tweet.getCreatedAt())+"</i></font></html>");
                labs.add(labels[i]);
                labels[i].setPreferredSize(new Dimension(670,45));
            }
        } catch (NullPointerException e) {}

    }

    Twitter tw;
    String opt;
    String KeyWord;
    Timer tm;
    JScrollPane sp;
    JTextPane tx;
    JPanel labs;
    List<Status> statuses;
    List<Tweet> tweets;
    listLocalImgRef lista;
    int last = 0;
    Query nquery;
    JLabel [] labels;

    ActionListener reload = new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            Thread thr = new Thread(){
            public void run() {
            if(opt.equals("tweets")) update(KeyWord);
            if(opt.equals("search")) search(nquery);
            }
            };
            thr.start();
            tm.restart();
        }
    };
}
